/**
 * 
 */
package cn.gov.msa.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

import org.activiti.engine.task.Task;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.io.FileUtils;


import cn.gov.msa.service.WorkFlowService;

/**
 * @author Administrator
 *
 */
public class WorkFlowServiceImpl implements WorkFlowService {

    ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
    
    @Override
	public List<Deployment> getWorkFlowDeployList() throws Exception {	    
		
	    List<Deployment> deployList = processEngine.getRepositoryService()
	    										.createDeploymentQuery()
	    										.orderByDeploymenTime().asc()
	    										.list();	
	    
		return deployList;
	}

    @Override
	public List<ProcessDefinition> getWorkDefinitionListByDeploymentId(String DeploymentId) throws Exception {		
	    
	    List<ProcessDefinition> processDefinition = processEngine.getRepositoryService()
													    		.createProcessDefinitionQuery()
													    		.deploymentId(DeploymentId)
													    		.list();
	    
		return processDefinition;
	}
	
	//部署流程
    @Override
    public String deployWithZip(File file, String name) throws FileNotFoundException{ 
    	String deploymentId = "";
    	
        FileInputStream in = new FileInputStream(file);  
        
//        InputStream in = this.getClass().getClassLoader().getResourceAsStream();  
        ZipInputStream zipInputStream = new ZipInputStream(in);  
        Deployment deployment = processEngine.getRepositoryService()//获取流程定义和部署对象相关的Service  
                        .createDeployment()//创建部署对象                   
                        .name(name)
                        .addZipInputStream(zipInputStream)//使用zip方式部署，将helloworld.bpmn和helloworld.png压缩成zip格式的文件  
                        .deploy();//完成部署  
        System.out.println("部署ID："+deployment.getId());//1  
        System.out.println("部署时间："+deployment.getDeploymentTime());
        deploymentId = deployment.getId();      
        
        return deploymentId;
    } 
    
    @Override
    public boolean deleteDeploy(String deploymentId)throws Exception{
    	boolean b = false;
    	
    	try{
	    	processEngine.getRepositoryService().deleteDeployment(deploymentId, true);
	    	
	    	int i = processEngine.getRepositoryService().createDeploymentQuery().deploymentId(deploymentId).list().size();
	    	
	    	b = i == 0 ? true: false;
    	}
    	catch(Exception e){
    		throw new Exception();
    	}
    	
    	return b;
    }

    @Override
    public InputStream showFlowImage(String deploymentId, String pathname) throws Exception {
    	String imagePath = null;
    	InputStream in = null;
    	
		List<String> names = processEngine.getRepositoryService()
				.getDeploymentResourceNames(deploymentId);
		
		String imageName = null;
		for(String name : names){
			System.out.println("name:" + name);
			if(name.indexOf(".png") > 0){
				imageName = name;
			}
		}
		
		System.out.println("imageName:" + imageName);
		if(imageName != null){
			File f = new File(pathname + "/" + imageName);
			in = processEngine.getRepositoryService()
					.getResourceAsStream(deploymentId, imageName);
		}
		
		return in;
	}
    
    
    //启动流程实例，并关联业务单
    @Override
    public String startFlow(String processDefinitionKey, String businessKey, String userID, List<String> nextUserIDs, boolean isApply) throws Exception {
		String result = "";
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userIDs", userID);

		ProcessInstance ins = processEngine.getRuntimeService()
				.startProcessInstanceByKey(processDefinitionKey, businessKey, map);
				
		result = ins.getId();


		if(isApply){   //启动实例直接结束任务（只适用业务申请的时候）
			String taskId = "";
			List<Task> tasks = findTask(userID);
			for (Task task : tasks) {
				String processInstanceId = task.getProcessInstanceId();
				if(processInstanceId.equals(result)){
					taskId = task.getId();
					break;
				}
			}
			
			if(!taskId.equals("")) {
				completeTask(taskId, nextUserIDs, false);
			}
				
		}
		
		return result;
	}
    
    @Override
    public boolean completeTask(String taskId, List<String> nextUserIDs, boolean isLast) throws Exception {
    	boolean b = false;
    	
    	if(isLast) {
    		processEngine.getTaskService().complete(taskId);
    	}
    	else{
    		if(nextUserIDs != null) {
	    		String userIDs = "";
	    		Map<String, Object> map = new HashMap<String, Object>();
	    		for (String nextUserID : nextUserIDs) {
	    			userIDs += nextUserID + ", ";
				}
	    		userIDs = userIDs.substring(0, userIDs.length() - 2);
				map.put("userIDs", userIDs);	    		
	    		
	    		processEngine.getTaskService().complete(taskId, map);
    		}
    	}
    	List<Task> task = processEngine.getTaskService().createTaskQuery().taskId(taskId).list();
    	
    	if(task.size() == 0) {
    		b = true;
    	}
    		
    	
    	return false;
	}
    
    //查询个人任务
    @Override
    public List<Task> findTask(String userID) throws Exception {
		List<Task> tasks = processEngine.getTaskService()
				.createTaskQuery()
//				.taskAssignee(userID)
				.taskCandidateUser(userID)
				.list();
		
		return tasks;
    }

    @Override
	public String getDeploymentIdByTaskId(String taskId) throws Exception {
		//使用任务ID，查询任务对象
		Task task = processEngine.getTaskService().createTaskQuery()//
					.taskId(taskId)//使用任务ID查询
					.singleResult();
		//获取流程定义ID
		String processDefinitionId = task.getProcessDefinitionId();
		//查询流程定义的对象
		ProcessDefinition pd = processEngine.getRepositoryService().createProcessDefinitionQuery()//创建流程定义查询对象，对应表act_re_procdef 
					.processDefinitionId(processDefinitionId)//使用流程定义ID查询
					.singleResult();
		
		String deploymentId = pd.getDeploymentId();
		
		return deploymentId;
	}
	

	/**
	 * 二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中
		 map集合的key：表示坐标x,y,width,height
		 map集合的value：表示坐标对应的值
	 */
    @Override
	public Map<String, Object> findCoordingByTask(String taskId) throws Exception {
		//存放坐标
		Map<String, Object> map = new HashMap<String,Object>();
		//使用任务ID，查询任务对象
		Task task = processEngine.getTaskService().createTaskQuery()//
					.taskId(taskId)//使用任务ID查询
					.singleResult();
		//获取流程定义的ID
		String processDefinitionId = task.getProcessDefinitionId();
		//获取流程定义的实体对象（对应.bpmn文件中的数据）
		ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity)processEngine.getRepositoryService().getProcessDefinition(processDefinitionId);
		//流程实例ID
		String processInstanceId = task.getProcessInstanceId();
		//使用流程实例ID，查询正在执行的执行对象表，获取当前活动对应的流程实例对象
		ProcessInstance pi = processEngine.getRuntimeService().createProcessInstanceQuery()//创建流程实例查询
					.processInstanceId(processInstanceId)//使用流程实例ID查询
					.singleResult();
		//获取当前活动的ID
		String activityId = pi.getActivityId();
		//获取当前活动对象
		ActivityImpl activityImpl = processDefinitionEntity.findActivity(activityId);//活动ID
		//获取坐标
		map.put("x", activityImpl.getX());
		map.put("y", activityImpl.getY());
		map.put("width", activityImpl.getWidth());
		map.put("height", activityImpl.getHeight());
		return map;
	}
    
    
    public static void main(String[] args) {
    	ProcessEngine processEngine1 = ProcessEngines.getDefaultProcessEngine();
    	
//    	processEngine1.getTaskService().complete("60013");
    	
    	
    	List<Task> task = processEngine1.getTaskService().createTaskQuery().taskId("60013").list();
    	
    	System.out.println(task);
    	
//		String processDefinitionKey = "level01nocheck";
//////
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("applyUser", "张三");
////		
//		ProcessInstance ins = processEngine1.getRuntimeService()
//				.startProcessInstanceByKey(processDefinitionKey, map);
//		
//		System.out.println("id:" + ins.getId());
//		
////		processEngine1.getRuntimeService().deleteProcessInstance("42501", "");
//    	
////    	42501
////    	List<org.activiti.engine.task.Task> tasks = processEngine1.getTaskService().createTaskQuery().deploymentId("").list();
////    	System.out.println(tasks);
//		
//		List<org.activiti.engine.task.Task> tasks = processEngine1.getTaskService()
//				.createTaskQuery()
//				.taskAssignee("张三")
//				.list();
//		
//		System.out.println(tasks);
	}
}
